﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MSHTML;


namespace myie.code.pharaoh.com
{
    public partial class FormIE : Form
    {
        public FormIE()
        {
            InitializeComponent();


        }
        
        private string _scriptPath;
        private string _libScript
        {
            get
            {
                return System.IO.File.ReadAllText(System.IO.Path.Combine(_scriptPath, "myieLib.js"));
            }
        }
        private void cbUrl_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                Go(cbUrl.Text);
            }

        }

        private void LoadFavorites()
        {
        	//System.IO.Directory.GetDirectories(
        	mnuFavorites.DropDownItems.Clear();
        	LoadFavoritesInPath(System.IO.Path.Combine(Application.StartupPath, "Favorites"),mnuFavorites);
        }

        private void LoadFavoritesInPath(string path,ToolStripMenuItem menu)
        {
        	//List<T>
        	string[] paths=System.IO.Directory.GetDirectories(path);
        	for (int i=0;i<paths.Length ;i++ ) {
        		ToolStripMenuItem menuItem=new ToolStripMenuItem(System.IO.Path.GetFileName(paths[i]));
        		menu.DropDownItems.Add(menuItem as ToolStripItem);
        		LoadFavoritesInPath(paths[i],menuItem);
        	}
        	string[] files=System.IO.Directory.GetFiles(path,"*.url");
        	for(int i=0;i<files.Length;i++)
        	{
        		string file=files[i];
        		string[] lines = System.IO.File.ReadAllLines(file,System.Text.Encoding.Default);
        		string url=null;
        		foreach(string line in lines)
        		{
        			if(line.StartsWith("URL="))
        			{
        				url=line.Substring(4);
        				break;
        			}
        		}
        		if(url!=null)
        		{
        		ToolStripMenuItem menuItemFile=new ToolStripMenuItem(System.IO.Path.GetFileNameWithoutExtension(file));
        		menuItemFile.Tag=url;
        		menuItemFile.Click+= new EventHandler(menuItemFile_Click);
        		menu.DropDownItems.Add(menuItemFile as ToolStripItem);                                                 
        		}
        	}
        }

        void menuItemFile_Click(object sender, EventArgs e)
        {
        	//throw new NotImplementedException();
        	ToolStripItem item=sender as ToolStripItem;
        	//MessageBox.Show(item.Tag.ToString());
        	Go(item.Tag as string);
        }
        
        private void Go(string url)
        {
            ie.Navigate(url);

            //ie.ActiveXInstance as IWebBrowser2
        }

        private void ie_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            if (e.Url.HostNameType != UriHostNameType.Unknown)
            {
                //                cbUrl.Text = e.Url.OriginalString;
                //                //_FrameName = e.TargetFrameName;
                //                _curUrl = e.Url.OriginalString;
                //                tmIE.Enabled = true;
                //                MessageBox.Show(e.Url.PathAndQuery);

            }

        }
        private string _curUrl;
        private string _FrameName;
        private void tmIE_Tick(object sender, EventArgs e)
        {
            //tmIE.Enabled = false;
            if (ie.ReadyState == WebBrowserReadyState.Complete)
            {
                tmIE.Enabled = false;
                //MessageBox.Show(_FrameName);
                ie.ObjectForScripting = script;
                script.LoadScript("myieLib.js");
                script.LoadScript("test.js");
                ie.Document.Body.MouseMove += new HtmlElementEventHandler(ie_Document_Body_MouseMove);
                //
                //MessageBox.Show(_curUrl);
            }

        }

        void ie_Document_Body_MouseMove(object sender, HtmlElementEventArgs e)
        {
            //throw new NotImplementedException();
            lbMouse.Text = e.ClientMousePosition.X.ToString() + "," + e.ClientMousePosition.Y.ToString();
            HtmlElement ele = ie.Document.GetElementFromPoint(new Point(e.ClientMousePosition.X, e.ClientMousePosition.Y));
            if (ele != null)
            {
                //ele.Parent
                List<string> eleStrs = new List<string>();
                while(ele!=null)
                {
                    eleStrs.Add(ElementToString(ele));
                    ele = ele.Parent;
                }
                eleStrs.Reverse();
                lbTag.Text = string.Join(">>", eleStrs.ToArray());
                //lbTag.Text = ElementToString(ele); //ele.TagName + ele.Id + "." + ele.GetAttribute("className");

            }
            else
            {
                lbTag.Text = "None";
            }

        }

        private string ElementToString(HtmlElement ele)
        {
            if(ele==null)
            {
                return "";
            }
            string r = ele.TagName;
            if(!string.IsNullOrEmpty(ele.Id))
            {
                r += "#" + ele.Id;
            }
            string className = ele.GetAttribute("className");
            if(!string.IsNullOrEmpty(className))
            {
                r += "." + className;
            }
            return r;
            //ele.Id
        }

        public Script script;
        private void ie_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            cbUrl.Text = ie.Url.OriginalString;
            if (e.Url.HostNameType != UriHostNameType.Unknown)
            {
                //cbUrl.Text = e.Url.OriginalString;
                _FrameName = e.TargetFrameName;
                _curUrl = e.Url.OriginalString;
                //tmIE.Enabled = true;
            }


        }

        private void FormIE_Load(object sender, EventArgs e)
        {
            //MessageBox.Show(((int)System.Windows.Forms.Keys.Control).ToString());
            script = new Script(this, this.ie);
            _scriptPath = System.IO.Path.Combine(Application.StartupPath, "script");
            ie.DocumentTitleChanged += new EventHandler(ie_DocumentTitleChanged);
            ie.ProgressChanged += new WebBrowserProgressChangedEventHandler(ie_ProgressChanged);
            LoadFavorites();
            //ie.Document.Window

            //ie.Click+= new EventHandler(ie_Click);
            //ie.MouseMove+= new MouseEventHandler(ie_MouseMove);
            //ie.Document.Window.Frames[] mshtml

            //win.execScript()
        }


        void ie_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
        {
            //e.
            cbUrl.Text = ie.Url.OriginalString;
            pbIE.Value = Convert.ToInt32(e.CurrentProgress * 100 / e.MaximumProgress);
            //pbIE.Maximum=//e.MaximumProgress;
        }



        void ie_DocumentTitleChanged(object sender, EventArgs e)
        {
            this.Text = ie.Document.Title;
        }


        void FormIEMouseMove(object sender, MouseEventArgs e)
        {
            lbMouse.Text = e.X.ToString() + "," + e.Y.ToString();
        }
        public void AddButton(string Name, string scriptName)
        {
            ToolStripMenuItem menuitem = new ToolStripMenuItem(Name);

            //System.Windows.Forms.Keys.D1 == 49
            menuitem.ShortcutKeys = (Keys)((int)System.Windows.Forms.Keys.Control + 49 + _userScriptCount);
            _userScriptCount++;
            menuitem.Tag = scriptName;
            menuitem.Click += new EventHandler(item_Click);
            mnuUserScript.DropDownItems.Add(menuitem);
            //mnuUserScript.it
            //Keys.
            // item.ShortcutKeys
            ToolStripItem item = new ToolStripButton(Name);
            item.Tag = scriptName;
            item.Click += new EventHandler(item_Click);
            toolStrip1.Items.Add(item);
        }
        int _userScriptCount = 0;
        public void ClearUserButton()
        {
            //toolStrip1.Items.r
            _userScriptCount = 0;
            mnuUserScript.DropDownItems.Clear();
            int count = toolStrip1.Items.Count;
            for (int i = 1; i < count; i++)
            {
                toolStrip1.Items.RemoveAt(1);
            }
        }

        void item_Click(object sender, EventArgs e)
        {
            ToolStripItem btn = sender as ToolStripItem;
            string scriptName = btn.Tag.ToString();
            //ie.Document.InvokeScript(scriptName);
            script.RunScript("PharaohTool." + scriptName + "();");
            //MessageBox.Show(btn.Tag.ToString());
        }

        void IeDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.HostNameType != UriHostNameType.Unknown)
            {
                if (e.Url.OriginalString == ie.Url.OriginalString)
                {
                    //MessageBox.Show(e.Url.AbsolutePath);
                    LoadScript();

                    //string mainPath=System.IO.Path.Combine(_scriptPath,e.Url.
                }
                else
                {
                    //MessageBox.Show("frame:"+e.Url);
                    //List<string> urls=new List<string>();
                    for (int i = 0; i < ie.Document.Window.Frames.Count; i++)
                    {
                        try
                        {
                            //urls.Add(ie.Document.Window.Frames[i].Url.OriginalString);
                            if (ie.Document.Window.Frames[i].Document.Url.OriginalString == e.Url.OriginalString)
                            {
                                IHTMLWindow2 winFrame = (IHTMLWindow2)ie.Document.Window.Frames[i].Document.Window.DomWindow;
                                LoadScript(winFrame, e.Url);
                                break;
                            }
                        }
                        catch (Exception exp)
                        {
                            //MessageBox.Show(exp.ToString());
                        }

                    }
                    //MessageBox.Show(string.Join("\n",urls.ToArray()));
                    //script.LoadScript("myieLib.js");
                    //script.LoadScript("test.js");
                }


            }
        }

        private void LoadScript()
        {
            ie.ObjectForScripting = script;
            ie.Document.Body.MouseMove += new HtmlElementEventHandler(ie_Document_Body_MouseMove);
            IHTMLWindow2 winMain = (IHTMLWindow2)ie.Document.Window.DomWindow;
            if (LoadScript(winMain, ie.Url))
            {
                RunScript(winMain, "PharaohTool.RegisterScript();");
            }
        }
        private bool LoadScript(IHTMLWindow2 win, Uri url)
        {
            if (win == null)
            {
                return false;
            }
            string jsFn = url.Host + "\\" + url.AbsolutePath.Replace('/', '#') + ".js";
            Log.LogInfo("LoadJs:" + jsFn);
            jsFn = System.IO.Path.Combine(_scriptPath, jsFn);
            //MessageBox.Show(jsFn);
            if (System.IO.File.Exists(jsFn))
            {
                RunScript(win, _libScript);
                RunScript(win, System.IO.File.ReadAllText(jsFn));
                return true;
            }
            return false;
        }
        private void RunScript(IHTMLWindow2 win, string script)
        {
            try
            {
                //MSHTML.IHTMLWindow2 win = (MSHTML.IHTMLWindow2)ie.Document.Window.DomWindow;
                win.execScript(script, "javascript");
            }
            catch (Exception exp)
            {
                MessageBox.Show("执行脚本错误!\n" + exp.ToString());
            }
        }

        private void 当前鼠标坐标ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //MousePosition
            Point ptIE = ie.PointToClient(MousePosition);
            string ptStr = ptIE.X.ToString() + "," + ptIE.Y.ToString();
            Clipboard.SetText(ptStr);
            lbLog.Text = "Copy:" + ptStr;
        }

        private void 拷贝当前元素类型ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetText(lbTag.Text);
            lbLog.Text = "Copy:" + lbTag.Text;
            //HtmlElement ele=
            Point pt = ie.PointToClient(MousePosition);

            HtmlElement ele = ie.Document.GetElementFromPoint(pt);
            if(ele!=null)
            {
                Log.LogInfo(ele.OuterHtml);
            }

        }

        private void 加载脚本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadScript();
        }

        private void mnuProxy_Click(object sender, EventArgs e)
        {
            mnuProxy.Checked = !mnuProxy.Checked;
            if(mnuProxy.Checked)
            {
                //proxy.RefreshIESettings("127.0.0.1:3128");
                proxy.RefreshIESettings("127.0.0.1:808");
            }
            else
            {
                proxy.RefreshIESettingsNoProxy();
            }
        }
    }
}
